package cj.web.lkg.controllers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.web.constants.SurveyTypeEnum;
import cj.web.lkg.dao.SurveyNewsDAO;
import cj.web.login.controllers.BaseController;

@Path("/surveyNews")
public class SurveyNewsController extends BaseController{

	private static Logger logger = Logger.getLogger(SurveyNewsController.class.getName());
	
	@Autowired
	private SurveyNewsDAO surveyNewsDao;

	/**
	 * 查看调查问卷
	 * @param model
	 * @param surveyId
	 * @param request
	 * @return
	 */
	@Get("show/{surveyId:[0-9]+}")
	public String show(Model model,@Param("surveyId") int surveyId){
		List<Map> surveylis = surveyNewsDao.querySurveyById(surveyId);
		if(surveylis!=null && surveylis.size()>0){
			Map surveyObj = surveylis.get(0);
			model.add("obj", surveyObj);
			String voteEnd = surveyObj.get("voteEnd").toString();
			int flag = DateUtils.compareDateWithNow(DateUtils.parse(voteEnd));//与活动时间比较是否结束
			if(flag<0){
				//活动结束
				model.add("returnCode",Constants.returnObj.returnCode.code_6);
				model.add("returnFlag", Constants.returnObj.returnFlag_flase);
				return "/views/surveyNew/survey_cover.vm";
			}else{
				model.add("returnCode",Constants.returnObj.returnCode.code_1);
			}
			
			String voteStart = surveyObj.get("voteStart").toString();
			int flagstartDate = DateUtils.compareDateWithNow(DateUtils.parse(voteStart));//与活动时间比较是否结束
			if(flagstartDate>0){
				//未开始
				model.add("returnCode", Constants.returnObj.returnCode.code_8);
				model.add("returnFlag", Constants.returnObj.returnFlag_flase);
				return "/views/surveyNew/survey_cover.vm";
			}else{
				model.add("returnCode",Constants.returnObj.returnCode.code_1);
			}
			
			
			model.add("returnFlag", Constants.returnObj.returnFlag_true);
		}else{
			model.add("returnCode",Constants.returnObj.returnCode.code_2);
			model.add("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "/views/surveyNew/survey_cover.vm";
	}
	
	/**
	 * 填写用户基本信息页面
	 * @param model
	 * @param surveyId
	 * @param request
	 * @return
	 */
	@Get("showSurveyPeople/{surveyId:[0-9]+}")
	public String showSurveyPeople(Model model,@Param("surveyId") int surveyId){
		model.add("surveyId", surveyId);
		return "/views/surveyNew/survey_login.vm";
	}
	
	/**
	 * 保存调查用户信息——生成考题
	 * @param model
	 * @param surveyId
	 * @param name
	 * @param phone
	 * @param companyGroup
	 * @param request
	 * @return
	 */
	@Post("saveSurveyPeople")
	public String saveSurveyPeople(@Param("surveyId") int surveyId,@Param("name") String name
			,@Param("phone") String phone){
		//,@Param("companyGroup") String companyGroup
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		try {
			int surveyPeopleId = 0;
			//是否存在电话号码
			List<Map> objList = surveyNewsDao.querySurveyPeopleByPhone(phone, surveyId);
			if(objList!=null && objList.size()>0){
				//调查用户ID
				surveyPeopleId = Integer.parseInt(objList.get(0).get("id").toString());
				
				//分数
				if(objList.get(0).get("score")!=null){
					//已有分数
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
				}else{
//					surveyNewsDao.updateSurveyPeopleByPhone(surveyPeopleId, name, phone, companyGroup, surveyId);
					initSurveyPeople(surveyId, surveyPeopleId);
				}
			}else{
//				//调查用户信息
				surveyPeopleId = surveyNewsDao.createSurveyPeople(null, surveyId, name, phone, "", phone);
//				//生成个人考题
				initSurveyPeople(surveyId, surveyPeopleId);
//				jo.put("returnFlag", Constants.returnObj.returnFlag_3);
			}
			
			jo.put("surveyPeopleId", surveyPeopleId);
			jo.put("surveyId", surveyId);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 生成个人考题
	 * @param surveyId			考试ID
	 * @param surveyPeopleId	考试人员ID
	 * @return
	 */
	private void initSurveyPeople(int surveyId,int surveyPeopleId){
		List<Map> surveylis = surveyNewsDao.querySurveyById(surveyId);
		if(surveylis!=null && surveylis.size()>0){
			Map surveyObj = surveylis.get(0);
			//考试题库号
			int surveyDepotId = Integer.parseInt(surveyObj.get("surveyDepotId").toString());
			
			//考试抽取题数
			int choiceCount = Integer.parseInt(surveyObj.get("choiceCount").toString());//选择题题数
			int judgementCount = Integer.parseInt(surveyObj.get("judgementCount").toString());//判断题题数
			int multiSelectCount = Integer.parseInt(surveyObj.get("multiSelectCount").toString());//多选题题数
			String l_subjectIds="";
			
			if(choiceCount>0){//选择题题数
				l_subjectIds+=createSurveySubject(surveyDepotId, choiceCount, SurveyTypeEnum.RADIO.getValue(), surveyId, surveyPeopleId);
			}
			
			if(multiSelectCount>0){//多选题题数
				l_subjectIds+=createSurveySubject(surveyDepotId, multiSelectCount, SurveyTypeEnum.CHECK.getValue(), surveyId, surveyPeopleId);
			}
			
			if(judgementCount>0){//判断题题数
				l_subjectIds+=createSurveySubject(surveyDepotId, judgementCount, SurveyTypeEnum.judge.getValue(), surveyId, surveyPeopleId);
			}
			
			//更新题目数
			surveyNewsDao.updateSubjectIdsBySurveyId(l_subjectIds, surveyId, surveyPeopleId);
		}
	}
	
	/**
	 * 生成考题信息
	 * @param surveyDepotId
	 * @param subjectCount
	 * @param isMutil
	 * @param surveyId
	 * @param surveyPeopleId
	 */
	private String createSurveySubject(int surveyDepotId,int subjectCount,int isMutil,int surveyId,int surveyPeopleId){
		//题号List
		List<Integer> reps = surveyNewsDao.queryDepotSubjectById(surveyDepotId,isMutil);
		
		//考试题库——题
		List<Map> surveyDepotSubjectlis = new ArrayList<Map>();
		
		//考题项SubjectIds
		List<Integer> subjectIds = new ArrayList<Integer>();
		String l_subjectIds="";
		if(reps.size()>subjectCount){
			//题数>选题数
			subjectIds = randomTopic(reps, subjectCount);
		}else{
			//题数<=选题数
			subjectIds = surveyNewsDao.querySurveyDepotSubjectIdById(surveyDepotId,isMutil);
			//打乱数组顺序 
			Collections.shuffle(subjectIds);
		}
		for(Integer subjectId:subjectIds){
			l_subjectIds+=subjectId+"@";
		}
		
		return l_subjectIds;
	}
	
	// 从List中随机出count个对象  
	private List<Integer> randomTopic(List<Integer> reps, int count) {  
	    // 创建一个长度为count(count<=list)的数组,用于存随机数  
	    int[] a = new int[count];  
	    // 利于此数组产生随机数  
	    int[] b = new int[reps.size()];  
	    int size = reps.size();  
	  
	    // 取样填充至数组a满  
	    for (int i = 0; i < count; i++) {  
	        int num = (int) (Math.random() * size); // [0,size)  
	        int where = -1;  
	        for (int j = 0; j < b.length; j++) {  
	            if (b[j] != -1) {  
	                where++;  
	                if (where == num) {  
	                    b[j] = -1;  
	                    a[i] = j;  
	                }  
	            }  
	        }  
	        size = size - 1;  
	    }  
	    // a填满后 将数据加载到rslist  
	    List<Integer> rslist = new ArrayList<Integer>();  
	    for (int i = 0; i < count; i++) {  
	    	Integer df = (Integer) reps.get(a[i]);  
	        rslist.add(df);  
	    }  
	    return rslist;  
	}  
	
	/**
	 * 答题界面
	 * @param model
	 * @param surveyId
	 * @param surveyPeopleId
	 * @param request
	 * @return
	 */
	@Get("showSurveyPeople/{surveyId:[0-9]+}/people/{surveyPeopleId:[0-9]+}")
	public String showSurveyPeople(Model model,@Param("surveyId") int surveyId,
			@Param("surveyPeopleId") int surveyPeopleId){
		
		List<Map> surveylis = surveyNewsDao.querySurveyById(surveyId);
		if(surveylis!=null && surveylis.size()>0){
			
			model.add("surveyId", surveyId);
			model.add("surveyPeopleId", surveyPeopleId);
			model.add("ksAt", Integer.parseInt(surveylis.get(0).get("ksAt").toString()));
			List<Map> surveyPeopleObj = surveyNewsDao.querySurveyPeopleById(surveyPeopleId);
			List<String> subjectIdlist = new ArrayList<String>();
			
			if(surveyPeopleObj!=null && surveyPeopleObj.size()>0){
				String subjectIds = surveyPeopleObj.get(0).get("subjectIds").toString();
				String[] subjectIdArray = subjectIds.split("@");
				subjectIdlist = Arrays.asList(subjectIdArray);
			}
			
			Map replis = returnSurveyDepotlis(surveyId, subjectIdlist);
			
			model.add("surveyRadiolis", replis.get("surveyRadiolis"));
			model.add("surveyChecklis", replis.get("surveyChecklis"));
			model.add("surveyJudgelis", replis.get("surveyJudgelis"));
			model.add("surveySubjectlis", replis.get("surveySubjectlis"));
		}
		
		return "/views/surveyNew/survey_cont.vm";
	}
	
	/**
	 * 调查题
	 * @param surveyId			选题
	 * @param surveyPeopleId	人ID
	 * @param isMutil			单选/多选/判断
	 * @return
	 */
	private Map returnSurveyDepotlis(int surveyId,List<String> subjectIdlist){
		Map rep = new HashMap();
		//单选
		List<Map> surveyRadiolis = new ArrayList<Map>();
		//多选
		List<Map> surveyChecklis = new ArrayList<Map>();
		//判断
		List<Map> surveyJudgelis = new ArrayList<Map>();
		//题信息
		List<Map> surveySubjectlis = surveyNewsDao.querySurveyDepotSubjectByInIds(subjectIdlist);
		//题项信息
		for(Map surveySubject:surveySubjectlis){
			int surveyDepotId = Integer.parseInt(surveySubject.get("surveyDepotId").toString());
			int subjectId = Integer.parseInt(surveySubject.get("id").toString());
			int isMutil = Integer.parseInt(surveySubject.get("isMutil").toString());
			String answers = surveySubject.get("answers").toString();//解析
			List<Map> surveyItemlis = surveyNewsDao.querySurveyDepotItemById(surveyDepotId, subjectId);
			surveySubject.put("items", surveyItemlis);
			surveySubject.put("answers", answers);//解析
			
			if(isMutil==SurveyTypeEnum.RADIO.getValue()){
				surveyRadiolis.add(surveySubject);
			}else if(isMutil==SurveyTypeEnum.CHECK.getValue()){
				surveyChecklis.add(surveySubject);
			}else if(isMutil==SurveyTypeEnum.judge.getValue()){
				surveyJudgelis.add(surveySubject);
			}
		}
		rep.put("surveyRadiolis", surveyRadiolis);
		rep.put("surveyChecklis", surveyChecklis);
		rep.put("surveyJudgelis", surveyJudgelis);
		
		rep.put("surveySubjectlis", surveySubjectlis);
		return rep;
	}
	
	/**
	 * 答案
	 * @return
	 */
	@Post("saveAnswer")
	public String saveAnswer(Model model,@Param("surveyId") int surveyId,
			@Param("surveyPeopleId") int surveyPeopleId,HttpServletRequest request){
		
		String answersIds = returnItemId(request).toString();
		
		surveyNewsDao.updateAnswersIdsBySurveyId(answersIds, surveyPeopleId);
		return "r:success/"+surveyPeopleId+"/surveyId/"+surveyId;
	}
	
	/**
	 * 获取除surveyId与surveyPeopleId参数的值
	 * @param request
	 * @return
	 */
	private StringBuffer returnItemId(HttpServletRequest request){
		StringBuffer strParameters = new StringBuffer();
		Map map = request.getParameterMap();
		Set keSet = map.entrySet();
		for (Iterator itr = keSet.iterator(); itr.hasNext();) {
			Map.Entry me = (Map.Entry) itr.next();
			Object ok = me.getKey();
			Object ov = me.getValue();
			String[] value = new String[1];
			if (ov instanceof String[]) {
				value = (String[]) ov;
			} else {
				value[0] = ov.toString();
			}
			for (int k = 0; k < value.length; k++) {
				if("surveyId".equals(ok)){
					continue;
				}
				if("surveyPeopleId".equals(ok)){
					continue;
				}
				
				if(strParameters.length()>0){
					strParameters.append(","+value[k]);
				}else{
					strParameters.append(value[k]);
				}
			}
		}
		
		return strParameters;
	}
	
	/**
	 * 成功
	 * @param model
	 * @param surveyPeopleId
	 * @return
	 */
	@Get("success/{surveyPeopleId:[0-9]+}/surveyId/{surveyId:[0-9]+}")
	public String surveySuccess(Model model,@Param("surveyPeopleId") int surveyPeopleId,@Param("surveyId") int surveyId){
		String errorIds ="";
		List<Map> repObjs = surveyNewsDao.querySurveyById(surveyId);//考试试卷
		int choiceFraction = Integer.parseInt(repObjs.get(0).get("choiceFraction").toString());//选择题分数
		int multiSelectFraction = Integer.parseInt(repObjs.get(0).get("multiSelectFraction").toString());//多选题分数
		int judgementFraction = Integer.parseInt(repObjs.get(0).get("judgementFraction").toString());//判断题分数
		int score=returnScore(repObjs);
		
		List<Map> surveyPeople = surveyNewsDao.querySurveyPeopleById(surveyPeopleId);
		if(surveyPeople!=null && surveyPeople.size()>0){
			String[] subjectIdArr = surveyPeople.get(0).get("subjectIds").toString().split("@");
			String[] answersIdArr = surveyPeople.get(0).get("answersIds").toString().split(",");
			
			List<String> subjectIdlist = Arrays.asList(subjectIdArr);
			List<String> answerslist = Arrays.asList(answersIdArr);
			
			//查询答案不匹配的
			List<Integer> subjectIds = surveyNewsDao.querySurveySubjectId(subjectIdlist,answerslist);
			
			//查找考卷说明
			List<Map> surveySubjectlis = surveyNewsDao.querySurveyDepotSubjectById(subjectIds);
			
			for(Map item:surveySubjectlis){
				int subjectId = Integer.parseInt(item.get("id").toString());
				int isMutil = Integer.parseInt(item.get("isMutil").toString());
				errorIds+=subjectId+"#";
				if(isMutil==SurveyTypeEnum.RADIO.getValue()){//选择题分数
					score-=choiceFraction;
				}else if(isMutil==SurveyTypeEnum.CHECK.getValue()){//多选题分数
					score-=multiSelectFraction;
				}else if(isMutil==SurveyTypeEnum.judge.getValue()){//判断题分数
					score-=judgementFraction;
				}
				
				List<Map> surveyItemlis = surveyNewsDao.querySurveyDepotItemById(subjectId);
				item.put("items", surveyItemlis);
			}
			
			surveyNewsDao.updateSurveyPeople(surveyPeopleId, score, errorIds);
			model.add("surveySubjectlis", surveySubjectlis);
			model.add("score", score);
			
//			if(true){
//				return "/views/surveyNew/survey_result.vm";
//			}
		}else{
			model.add("surveySubjectlis", null);
			model.add("score", 0);
		}
		
		return "/views/surveyNew/survey_result_bak.vm";
	}
	
	/**
	 * 返回个人总分数
	 * @param surveyPeopleId
	 * @return
	 */
	private int returnScore(List<Map> repObjs){
		int score=0;
		
		int choiceFraction = Integer.parseInt(repObjs.get(0).get("choiceFraction").toString());//选择题分数
		int choiceCount = Integer.parseInt(repObjs.get(0).get("choiceCount").toString());//判断题分数
		int multiSelectFraction = Integer.parseInt(repObjs.get(0).get("multiSelectFraction").toString());//多选题分数
		int multiSelectCount = Integer.parseInt(repObjs.get(0).get("multiSelectCount").toString());//选择题分数
		int judgementFraction = Integer.parseInt(repObjs.get(0).get("judgementFraction").toString());//判断题分数
		int judgementCount = Integer.parseInt(repObjs.get(0).get("judgementCount").toString());//多选题分数
		
		score=choiceFraction*choiceCount+multiSelectFraction*multiSelectCount+judgementFraction*judgementCount;
		
		return score;
	}
}